<template>
  <Dialog v-model="dialogVisible" title="成绩计算" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="评价计划" prop="planId">
            <el-select v-model="formData.planId" placeholder="请选择评价计划">
              <el-option label="2023年第四季度电工评价" value="1" />
              <el-option label="2023年第四季度焊工评价" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价批次" prop="batchId">
            <el-select v-model="formData.batchId" placeholder="请选择评价批次">
              <el-option label="第一批次" value="1" />
              <el-option label="第二批次" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计算模式" prop="calculateMode">
            <el-radio-group v-model="formData.calculateMode">
              <el-radio :value="1">按科目权重</el-radio>
              <el-radio :value="2">平均分计算</el-radio>
              <el-radio :value="3">自定义规则</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计算范围" prop="calculateScope">
            <el-radio-group v-model="formData.calculateScope">
              <el-radio :value="1">全部考生</el-radio>
              <el-radio :value="2">指定考生</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 科目权重配置 -->
      <el-divider content-position="left" v-if="formData.calculateMode === 1">
        科目权重配置
      </el-divider>
      <el-table 
        v-if="formData.calculateMode === 1"
        :data="subjectWeights" 
        border 
        style="width: 100%; margin-bottom: 20px;"
      >
        <el-table-column prop="subjectName" label="科目名称" width="200" />
        <el-table-column prop="subjectType" label="科目类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getSubjectTypeName(row.subjectType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重" width="150">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.weight" 
              :min="0" 
              :max="100" 
              :precision="1"
              size="small"
            />
            <span style="margin-left: 5px;">%</span>
          </template>
        </el-table-column>
        <el-table-column prop="passScore" label="及格分数" width="120" />
        <el-table-column prop="totalScore" label="满分" width="100" />
        <el-table-column prop="required" label="必考" width="80">
          <template #default="{ row }">
            <el-tag :type="row.required ? 'success' : 'info'">
              {{ row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 自定义计算规则 -->
      <el-divider content-position="left" v-if="formData.calculateMode === 3">
        自定义计算规则
      </el-divider>
      <div v-if="formData.calculateMode === 3" style="margin-bottom: 20px;">
        <el-form-item label="计算公式" prop="customFormula">
          <el-input
            v-model="formData.customFormula"
            type="textarea"
            :rows="3"
            placeholder="请输入计算公式，如：理论成绩*0.4 + 实操成绩*0.6"
          />
        </el-form-item>
        <el-form-item label="附加条件" prop="additionalConditions">
          <el-checkbox-group v-model="formData.additionalConditions">
            <el-checkbox label="allPass">所有科目都必须及格</el-checkbox>
            <el-checkbox label="mainPass">主要科目必须及格</el-checkbox>
            <el-checkbox label="bonusScore">考虑加分项目</el-checkbox>
            <el-checkbox label="penaltyScore">考虑扣分项目</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>
      
      <!-- 指定考生 -->
      <el-divider content-position="left" v-if="formData.calculateScope === 2">
        选择考生
      </el-divider>
      <div v-if="formData.calculateScope === 2" style="margin-bottom: 20px;">
        <el-transfer
          v-model="formData.selectedCandidates"
          :data="candidateList"
          :titles="['可选考生', '已选考生']"
          :props="{ key: 'id', label: 'name' }"
          filterable
          filter-placeholder="搜索考生"
        />
      </div>
      
      <el-form-item label="计算说明" prop="calculateDesc">
        <el-input
          v-model="formData.calculateDesc"
          type="textarea"
          :rows="2"
          placeholder="请输入计算说明"
        />
      </el-form-item>
    </el-form>
    
    <!-- 计算结果预览 -->
    <el-divider content-position="left" v-if="previewResults.length > 0">
      计算结果预览
    </el-divider>
    <el-table 
      v-if="previewResults.length > 0"
      :data="previewResults" 
      border 
      style="width: 100%; margin-bottom: 20px;"
      max-height="300"
    >
      <el-table-column prop="candidateName" label="考生姓名" width="120" />
      <el-table-column prop="theoryScore" label="理论成绩" width="100" />
      <el-table-column prop="practiceScore" label="实操成绩" width="100" />
      <el-table-column prop="totalScore" label="总成绩" width="100">
        <template #default="{ row }">
          <span :style="{ color: row.totalScore >= 60 ? '#67c23a' : '#f56c6c' }">
            {{ row.totalScore }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="result" label="评价结果" width="100">
        <template #default="{ row }">
          <el-tag :type="row.result === '合格' ? 'success' : 'danger'">
            {{ row.result }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="等级" width="100" />
    </el-table>
    
    <template #footer>
      <el-button @click="previewCalculate" type="info" :loading="previewLoading">预览计算</el-button>
      <el-button @click="submitCalculate" type="primary" :loading="formLoading">确认计算</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const previewLoading = ref(false)
const formRef = ref()
const formData = ref({
  planId: '',
  batchId: '',
  calculateMode: 1,
  calculateScope: 1,
  customFormula: '',
  additionalConditions: [] as string[],
  selectedCandidates: [] as string[],
  calculateDesc: ''
})
const formRules = ref({
  planId: [{ required: true, message: '评价计划不能为空', trigger: 'change' }],
  batchId: [{ required: true, message: '评价批次不能为空', trigger: 'change' }]
})

// 科目权重数据
const subjectWeights = ref([
  {
    subjectId: '1',
    subjectName: '理论考试',
    subjectType: 1,
    weight: 40.0,
    passScore: 60,
    totalScore: 100,
    required: true
  },
  {
    subjectId: '2',
    subjectName: '实操考试',
    subjectType: 2,
    weight: 60.0,
    passScore: 60,
    totalScore: 100,
    required: true
  }
])

// 考生列表
const candidateList = ref([
  { id: '1', name: '张三 - 身份证号：123456789012345678' },
  { id: '2', name: '李四 - 身份证号：123456789012345679' },
  { id: '3', name: '王五 - 身份证号：123456789012345680' }
])

// 预览结果
const previewResults = ref([])

const getSubjectTypeName = (type: number) => {
  const typeMap = { 1: '理论', 2: '实操', 3: '综合' }
  return typeMap[type] || '-'
}

const previewCalculate = () => {
  previewLoading.value = true
  // 模拟计算过程
  setTimeout(() => {
    previewResults.value = [
      {
        candidateName: '张三',
        theoryScore: 85,
        practiceScore: 78,
        totalScore: 80.6,
        result: '合格',
        level: '良好'
      },
      {
        candidateName: '李四',
        theoryScore: 72,
        practiceScore: 58,
        totalScore: 63.2,
        result: '合格',
        level: '及格'
      },
      {
        candidateName: '王五',
        theoryScore: 58,
        practiceScore: 55,
        totalScore: 56.2,
        result: '不合格',
        level: '不及格'
      }
    ] as any
    previewLoading.value = false
  }, 1500)
}

const submitCalculate = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  formLoading.value = true
  try {
    // TODO: 执行成绩计算
    console.log('执行成绩计算:', formData.value)
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

const resetForm = () => {
  formData.value = {
    planId: '',
    batchId: '',
    calculateMode: 1,
    calculateScope: 1,
    customFormula: '',
    additionalConditions: [],
    selectedCandidates: [],
    calculateDesc: ''
  }
  previewResults.value = []
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

defineExpose({ open })
</script> 